package x.ovo.wechat.bot.core;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import x.ovo.wechat.bot.common.Context;
import x.ovo.wechat.bot.common.entity.event.MessageEvent;
import x.ovo.wechat.bot.common.entity.message.Message;
import x.ovo.wechat.bot.common.entity.message.RawMessage;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.http.WechatApi;

import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class MessageConsumer implements Runnable {

    public static final ReentrantLock lock = new ReentrantLock();
    private static final Condition single = lock.newCondition();
    // 消息队列
    private static final ConcurrentLinkedQueue<RawMessage> queue = new ConcurrentLinkedQueue<>();
    private final Context context;
    private final WechatApi api;
    private final MessageConvertor converter;

    public MessageConsumer(Context context) {
        this.context = context;
        this.api = context.getApi();
        this.converter = new MessageConvertor(context);
    }

    public static void addMessages(Collection<RawMessage> messages) {
        queue.addAll(messages);
    }

    @Override
    public void run() {
        log.info("消息消费线程已启动");
        while (this.context.isRunning()) {
            try {
                if (queue.isEmpty()) {
                    ThreadUtil.safeSleep(500);
                    continue;
                }

                // 消息队列不为空，取出消息
                RawMessage rawMessage = queue.poll();
                // 如果消息时间小于上次退出时间，则进行下一次循环
//                if (rawMessage.getCreateTime() < this.context.getLoginSession().getLastExitTime()) continue;
                // 转换原始消息为消息类
                Message message = this.converter.convert(rawMessage);
                // 状态通知，每隔5分钟同步已读消息
                if (rawMessage.getCreateTime() / 60 % 5 == 0) {
                    this.api.statusNotify(message.getFromUser().getUserName());
                }
                log.info("{} -> {}: [{}] {}", message.getFromName(), message.getToName(), message.getType().getName(), message.getContent());
                // 如果是指令，则执行指令
                if (message instanceof TextMessage && message.getContent().startsWith("/")) {
                    this.context.getCommandManager().execute((TextMessage) message);
                    continue;
                }
                // 发送事件
                this.context.getEventManager().callEvent(new MessageEvent<>(message));
            } catch (Exception e) {
                log.error("消息处理失败", e);
            }
        }
    }
}
